package com.genersoft.iot.vmp.conf.redis.serializer;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.lang.NonNull;

/**
 * <p>带前缀的字符串序列化器.</p>
 *
 * @author <a href="mailto:82649941@163.com">C.Y.</a>
 */
public class PrefixKeySerializer implements RedisSerializer<String> {

    /**
     * <p>字符集.</p>
     */
    private final Charset charset;

    /**
     * <p>前缀.</p>
     */
    private final String prefix;

    /**
     * <p>默认构造方法.</p>
     */
    public PrefixKeySerializer() {
        this(StandardCharsets.UTF_8, "");
    }

    /**
     * <p>指定前缀的构造方法.</p>
     *
     * @param prefix 前缀
     */
    public PrefixKeySerializer(String prefix) {
        this(StandardCharsets.UTF_8, prefix);
    }

    /**
     * <p>指定字符集和前缀的构造方法.</p>
     *
     * @param charset 字符集
     * @param prefix 前缀
     */
    public PrefixKeySerializer(Charset charset, String prefix) {
        this.charset = charset;
        this.prefix = prefix;
    }

    @Override
    public byte[] serialize(String string) throws SerializationException {
        return (string == null ? null : (prefix + string).getBytes(charset));
    }

    @Override
    public String deserialize(byte[] bytes) throws SerializationException {
        return (bytes == null ? null : new String(bytes, charset).replaceFirst(prefix, ""));
    }

    @Override
    @NonNull
    public Class<?> getTargetType() {
        return String.class;
    }
}
